package cool.tianyou.blue.bird.util;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Looper;
import android.provider.Settings;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.preference.PreferenceManager;

import com.alibaba.fastjson.JSONObject;

import cool.tianyou.blue.bird.activity.MainActivity;
import cool.tianyou.blue.bird.codec.digest.DigestUtils;
import cool.tianyou.blue.bird.constant.Constant;
import cool.tianyou.blue.bird.LocalStorage;
import cool.tianyou.blue.bird.activity.LoginActivity;
import cool.tianyou.blue.bird.model.ApiResult;
import cool.tianyou.blue.bird.model.CommonMessage;
import cool.tianyou.blue.bird.model.Device;
import cool.tianyou.blue.bird.model.Log;
import cool.tianyou.blue.bird.model.Message;
import cool.tianyou.blue.bird.model.NotificationData;
import cool.tianyou.blue.bird.model.ResponseEntity;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Util {

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void obtainPublicKey(Context context, Consumer<List<Device>> consumer) {
        HttpUtil.get(context, null, "/device/pushable", apiResult -> {
            List<Device> devices = JSONUtil.parseArray(apiResult.getData(), Device.class);
            LocalStorage.devices.clear();
            LocalStorage.devices.addAll(devices);
            consumer.accept(devices);
        });

    }

    public static void showToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }

    public static void toLogin(Context context) {
        showToast(context, "登录过期，请重新登录");
        context.startActivity(new Intent(context, LoginActivity.class));
        SpUtil.putString(context, Constant.SP_CONSTANT.USER_ID, "");
        SpUtil.putString(context, Constant.SP_CONSTANT.TOKEN, "");
        MainActivity.instance.finish();
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void sendMessage(CommonMessage message, Context context) {
        if (!checkLoginState(context) || !openMessagePush(context)) {
            return;
        }
        LocalStorage.putMessage(message);
        obtainPublicKey(context, devices -> {
            Map<String, CommonMessage> dispatchData = message
                    .setNotification(message.getNotificationData())
                    .genDispatchData(devices);

            Log log = message.genLog();
            log.setPushedDevices(null);
            LogUtil.recordLog(log,context);
            HttpUtil.post(context, dispatchData, "/notification/push",
                    apiResult -> {
                        log.setPushedDevices(JSONUtil.parseArray(apiResult.getData(), String.class));
                        LogUtil.updateLog();
                    });
        });
    }

    /**
     * 推送消息给指定的设备
     *
     * @param message  消息
     * @param context  上下文
     * @param deviceId 设备id
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void sendMessage(CommonMessage message, Context context, Integer deviceId) {
        if (!checkLoginState(context) || !openMessagePush(context)) {
            return;
        }
        LocalStorage.putMessage(message);
        obtainPublicKey(context, devices -> {
            Optional<Device> first = devices.stream().filter(device -> Objects.equals(device.getId(), deviceId)).findFirst();
            first.ifPresent(targetDevice -> {
                Map<String, CommonMessage> dispatchData = message
                        .setNotification(message.getNotificationData())
                        .genDispatchData(Collections.singletonList(targetDevice));

                HttpUtil.post(context, dispatchData, "/notification/push",
                        apiResult -> {
                            Log log = message.genLog();
                            log.setPushedDevices(JSONUtil.parseArray(apiResult.getData(), String.class));
                            LogUtil.recordLog(log,context);
                        });
            });
        });
    }


    public static String getDeviceId(Context context) {
        String androidId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String deviceId = DigestUtils.md5Hex(androidId + (Build.BRAND + android.os.Build.MODEL + Build.VERSION.RELEASE).replace(' ', '_'));
        Constant.USER_INFO.DEVICE_INFO = deviceId;
        Constant.USER_INFO.BRAND = Build.BRAND;
        Constant.USER_INFO.MODEL = Build.MODEL;
        return deviceId;
    }

    private static boolean openMessagePush(Context context) {
        return Objects.equals(true, SpUtil.get(context, Constant.SP_CONSTANT.MESSAGE_PUSH_STATUS, false));
    }

    public static boolean checkLoginState(Context context) {
        String token = SpUtil.getString(context, Constant.SP_CONSTANT.TOKEN, "");
        String userId = SpUtil.getString(context, Constant.SP_CONSTANT.USER_ID, "");
        return !token.equals("") && !userId.equals("");

    }


}
